<?php
	function set_message($message, $type, $location){
		global $login_message;

		if($location == 1)
			echo "<div id='message' class='".$type."'><span></span><a>".$message."</a></div>";
		else
			$login_message = "<div id='message' class='".$type."'><span></span><a>".$message."</a></div>";
	}
	
	function api_call($method, $parameters=NULL){
		$url = LABORA_API_BASE_URL . "?method=" . $method;
		
		switch($method){
			case "authenticate_user":
				$method_parameters = array('username','password');
				break;
			case "get_user_id_by_username":
				$method_parameters = array('username');
				break;
			case "get_users":
			case "get_pxeimages":
			case "get_motherboards":
				$method_parameters = array('filter');
				break;
			case "get_resources":
				$method_parameters = array('filter', 'type');
				break;
			case "update_user":
				$method_parameters = array('user_id', 'new_user_data');
				break;
			case "add_user":
				$method_parameters = array('username', 'name', 'email', 'password', 'gidnumber', 'homedirectory');
				break;
			case "delete_user":
			case "get_my_reservations":
				$method_parameters = array('user_id');
				break;
			case "cancel_reservation":
				$method_parameters = array('reservation_id');
				break;
			case "add_slice":
				$method_parameters = array('slice_data', 'expire_date');
				break;
			case "add_user_to_slice":
				$method_parameters = array('user_id', 'slice_id');
				break;
			case "add_resource_to_slice":
				$method_parameters = array('resource_id', 'slice_id');
				break;
			case "create_reservation":
				$method_parameters = array('user_id','slice_id','begin_time','end_time');
				break;
			case "get_free_resources":
				$method_parameters = array('begin_time','end_time','type');
				break;
			case "delete_resource":
				$method_parameters = array('resource_id');
				break;
			case "update_resource":
				$method_parameters = array('resource_id', 'resource_new_data');
				break;
			case "add_resource":
				$method_parameters = array('type', 'resource_data');
				break;
			case "add_pxeimage":
				$method_parameters = array('pxeimage_data');
				break;
			case "delete_pxeimage":
				$method_parameters = array('pxeimage_id');
				break;
			case "update_pxeimage":
				$method_parameters = array('pxeimage_id', 'pxeimage_new_data');
				break;
			case "add_motherboard":
				$method_parameters = array('motherboard_data');
				break;
			case "delete_motherboard":
				$method_parameters = array('motherboard_id');
				break;
			case "update_motherboard":
				$method_parameters = array('motherboard_id', 'motherboard_new_data');
				break;
			case "resolve_ldap_pendecy":
				$method_parameters = array('pendency_id');
				break;
		}
		
		for($i=0; $i < count($parameters); $i++){
			$array_key_name = array_keys($parameters)[$i];
			
			if(in_array($array_key_name, $method_parameters, true)){
				$param_value = $parameters[''.$array_key_name.''];
				
				if(is_array($param_value))
					$param_value = json_encode($param_value);
				
				$param_value = urlencode($param_value);
				$url .= "&".$array_key_name."=".$param_value."";
			}
		}
		
		$app_return = file_get_contents($url);
		$app_return = json_decode($app_return, true);

		return $app_return;
	}
	
	if(isset($_POST['sbmt_login'])){
		$username = $_POST['username'];
		$password = $_POST['password'];
		
		if(!strstr($username,"@".ISLAND_PREFIX.""))
			$username = "".$username."@".ISLAND_PREFIX."";
		
		$parameters	=	array(
							'username' => $username,
							'password' => $password
						);
						
		$authentication = api_call("authenticate_user", $parameters);
		
		if($authentication['method_result'] == false)
			set_message('Invalid User Name, Password or institution.','error',0);
		else{
			$user_data = api_call("get_users", array('filter' => array($authentication['method_result'])));
			
			if($user_data['method_result'][0]['enable'] == 't'){
				$_SESSION[''.SECURITY_SESSION.''] = array(
														'username' => $username,
														'user_id' => $authentication['method_result'],
														'admin' => $user_data['method_result'][0]['admin']
													);
													
				Header('Location: index.php?page=reservation');
			}else
				set_message('Account not approved yet. Please, contact your testbed administrator.','alert',0);
		}
	}
	
	function validating_authentication($type=NULL){
		if($type == 'admin'){
			if($_SESSION[''.SECURITY_SESSION.'']['admin'] != 't')
				Header('Location: index.php');
		}
		
		if(!$_SESSION[''.SECURITY_SESSION.''])
			Header('Location: index.php');
	}
	
	function bread_crumbs($position = NULL, $first = FALSE) {
		$page = (isset($position) && $position != NULL) ? $position : (isset($_GET['page']) ? $_GET['page'] : NULL);
		
		switch($page){
			default:
				$location = NULL;
				break;
			case "home":
				$location = "default";
				$bc_title = "Home";
				break;
			case "request_account":
				$location = "home";
				$bc_title = "Request account";
				break;
			case "forgot_password":
				$location = "home";
				$bc_title = "Forgot password";
				break;
			case "resources":
				$location = "home";
				$bc_title = "Island resources";
				break;
			case "policy":
				$location = "home";
				$bc_title = "Island policy";
				break;
			case "contact":
				$location = "home";
				$bc_title = "Island contact";
				break;
			case "my_account":
				$location = "home";
				$bc_title = "My account";
				break;
			case "reservation":
				$location = "home";
				$bc_title = "Reservation";
				break;
			case "my_reservations":
				$location = "home";
				$bc_title = "My reservations";
				break;
			case "manager_user":
				$location = "home";
				$bc_title = "Manager users";
				break;
			case "edit_user":
				$location = "manager_user";
				$bc_title = "Edit user";
				break;
			case "pendency":
				$location = "home";
				$bc_title = "Island pending";
				break;
			case "manager_resources":
				$location = "home";
				$bc_title = "Manager resources";
				break;
			case "edit_resource":
				$location = "manager_resources";
				$bc_title = "Edit resource";
				break;
			case "add_resource":
				$location = "manager_resources";
				$bc_title = "Add resource";
				break;
			case "manager_pxeimages":
				$location = "manager_resources";
				$bc_title = "Manager pxeimages";
				break;
			case "add_pxeimage":
				$location = "manager_pxeimages";
				$bc_title = "Add pxeimage";
				break;
			case "edit_pxeimage":
				$location = "manager_pxeimages";
				$bc_title = "Edit pxeimage";
				break;
			case "manager_motherboards":
				$location = "manager_resources";
				$bc_title = "Manager motherboards";
				break;
			case "add_motherboard":
				$location = "manager_motherboards";
				$bc_title = "Add motherboard";
				break;
			case "edit_motherboard":
				$location = "manager_motherboards";
				$bc_title = "Edit motherboard";
				break;
		}
		
		$bread_crumbs = "";
		if($location != NULL) {
			$bread_crumbs = bread_crumbs($location);
			
			if(!$first)
				$bread_crumbs .= " <a href='index.php?page=".$page."'>".$bc_title."</a> »";
		}
		
		return $bread_crumbs;
	}
	
	function send_mail($sender, $receiver, $subject, $message){
		require("phpmailer/class.phpmailer.php");

		$mail = new PHPMailer();

		$mail->IsSMTP();
		$mail->Host = "localhost";
		$mail->From = $sender['email'];
		$mail->FromName = $sender['name'];
		
		for($i = 0; $i < count($receiver); $i++)
			$mail->AddAddress($receiver[$i]['email'], $receiver[$i]['name']);
			
		$mail->IsHTML(true);
		$mail->CharSet = 'iso-8859-1';
		$mail->Subject  = $subject;
		$mail->Body = $message;

		$send = $mail->Send();

		$mail->ClearAllRecipients();
		$mail->ClearAttachments();

		if($send)
			return TRUE;
		else
			return FALSE;
	}
	
	function mk_drawCalendar($m,$y){
		if ((!$m) || (!$y)){ 
			$m = date("m",mktime());
			$y = date("Y",mktime());
		}

		/*== get what weekday the first is on ==*/
		$tmpd = getdate(mktime(0,0,0,$m,1,$y));
		$month = $tmpd["month"]; 
		$firstwday= $tmpd["wday"];

		$lastday = mk_getLastDayofMonth($m,$y);
		$formaction = "index.php?page=reservation";

		?>
	
		<table cellpadding="2" cellspacing="0" border="1">
		<tr><td colspan="7" bgcolor="#CCCCDD">
			<table cellpadding="0" cellspacing="0" border="0" width="100%">
			<tr><th width="20"><a href="<?php echo $formaction; ?>&m=<?php $a=(($m-1)<1) ? 12 : $m-1; echo $a; ?>&y=<?php $b=(($m-1)<1) ? $y-1 : $y; echo $b; ?>">&lt;&lt;</a></th>
			<th><div align="center"><?php echo "$month"; ?></div></th>
			<th width="20"><a href="<?php echo $formaction; ?>&m=<?php $c=(($m+1)>12) ? 1 : $m+1; echo $c; ?>&y=<?php $d=(($m+1)>12) ? $y+1 : $y; echo $d; ?>">&gt;&gt;</a></th>
			</tr></table>
		</td></tr>

		<tr><th width=30 class="tcell">Sun</th><th width=30 class="tcell">Mon</th>
			<th width=30 class="tcell">Tue</th><th width=30 class="tcell">Wen</th>
			<th width=30 class="tcell">Thu</th><th width=30 class="tcell">Fri</th>
			<th width=30 class="tcell">Sat</th></tr>

		<?php $d = 1;
			$wday = $firstwday;
			$firstweek = true;

			/*== loop through all the days of the month ==*/
			while ( $d <= $lastday) {

				/*== set up blank days for first week ==*/
				if ($firstweek) {
					echo "<tr>";
					for ($i=1; $i<=$firstwday; $i++) 
					{ echo "<td><font size=2>&nbsp;</font></td>"; }
					$firstweek = false;
				}

				/*== Sunday start week with <tr> ==*/
				if ($wday==0) { echo "<tr>"; }

				/*== check for event ==*/  
				echo "<td class='tcell'>";
				if(strlen($m)<2) { $m= "0" . $m; }
				if(strlen($d)<2) { $d= "0" . $d; }
				/* href=\"$formaction&m=$m&y=$y#\" */
				/* href=\"#calendar\" */
				echo "<a href=\"#calendar\" onClick=\"document.f.start_date.value='$y-$m-$d';\">$d</a>";
				echo "</td>\n";

				/*== Saturday end week with </tr> ==*/
				if ($wday==6) { echo "</tr>\n"; }

				$wday++;
				$wday = $wday % 7;
				$d++;
			}
		?>
		</tr></table>
	<?php
	}

	function mk_getLastDayofMonth($mon,$year){
		for ($tday=28; $tday <= 31; $tday++){
			$tdate = getdate(mktime(0,0,0,$mon,$tday,$year));
			if ($tdate["mon"] != $mon) 
			{ break; }

		}
		$tday--;

		return $tday;
	}

?>
